package com.kakarote.crm9.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.Map;

public class HttpUtils {

    public String doGet(String url, Map<String, String> params, Map<String, String> headers) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (params != null) {
                System.out.println("请求参数【{}】"+params);
                for (String param : params.keySet()) {
                    builder.addParameter(param, params.get(param));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
           System.out.println("请求路径【{}】"+uri);
            HttpGet httpGet = new HttpGet(uri);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(7200).setSocketTimeout(7200).build();
            httpGet.setConfig(requestConfig);
            //添加请求头
            if(headers != null) {
                for(String header :headers.keySet()) {
                    httpGet.addHeader(header, headers.get(header));
                }
            }
            System.out.println("开始执行Get请求");
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("请求成功，响应实体【{}】"+resultString);
            }
        } catch (Exception e) {
           System.out.println("Get请求发生异常"+e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
               System.out.println("response为空"+e);
//                throw new BusinessException("response为空");
            }
        }
        return resultString;
    }


    public String post(String serviceUrl,String body){
        System.out.println("请求网关的路径:【{}】"+serviceUrl);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String ssd =null;
//        Integer round = (int)((Math.random()*9+1)*1000000000);
//        AppId appId = appIdDao.get("1");
//        AccessToken accessToken = accessTokenDao.get("1");
        try {
            HttpPost httpPost = new HttpPost(serviceUrl);
            //设置请求及响应时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(720000).setSocketTimeout(720000).build();
            httpPost.setConfig(requestConfig);
            //设置请求头
            httpPost.setHeader("Content-type", "application/json");
//            String sd=accessTokenDao.get("1").getAccessToken();
//            String headerToken = sd;//先获取token"4235AC51B6ADD5140214BB06C2941C0C"
//            String headerSerialNo = "1190"+round;//流水号段(商户的唯一标识)+10位数字
//            httpPost.setHeader("Authorization",headerToken);
//            httpPost.setHeader("serial_no",headerSerialNo);
            //添加请求体
            StringEntity stringEntity = new StringEntity(body, "UTF-8");
            System.out.println("请求体是【{}】"+stringEntity);
            httpPost.setEntity(stringEntity);
            String result = null;
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = getResultStr(response, entity);
            ssd= result;
        } catch (UnsupportedEncodingException e) {
            System.out.println("错误信息为：[{}]"+e);
        } catch (IOException e) {
            System.out.println("错误信息为：[{}]"+e);
        } finally{
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                System.out.println("response为空"+e);
            }
        }
        return ssd;
    }
    public static String getResultStr(HttpResponse response, HttpEntity entity) throws IOException{
        String result = "";
        int httpCode = response.getStatusLine().getStatusCode();
        if(200 == httpCode){
            result = EntityUtils.toString(entity,"UTF-8").trim();
            System.out.println("服务器请求成功,返回结果:{}"+result);
        }else{
            result = EntityUtils.toString(entity,"UTF-8").trim();
            System.out.println("失败HTTP状态码:【{}】失败信息【{}】"+response.getStatusLine().getStatusCode()+result);
        }
        return result;
    }



}
